//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.common.port.adapter.persistence.hibernate;

import com.saasovation.common.domain.model.DomainEvent;
import com.saasovation.common.event.EventSerializer;
import com.saasovation.common.event.EventStore;
import com.saasovation.common.event.StoredEvent;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.util.List;

public class HibernateEventStore implements EventStore {

    private final SessionFactory sessionFactory;

    public HibernateEventStore(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
    }

    @Override
    public List<StoredEvent> allStoredEventsBetween(long aLowStoredEventId, long aHighStoredEventId) {
        Query<StoredEvent> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.event.StoredEvent as _obj_ "
                        + "where _obj_.eventId between :lowEventId and :highEventId "
                        + "order by _obj_.eventId", StoredEvent.class);
        query.setParameter("lowEventId", aLowStoredEventId);
        query.setParameter("highEventId", aHighStoredEventId);
        return query.list();
    }

    @Override
    public List<StoredEvent> allStoredEventsSince(long aStoredEventId) {
        Query<StoredEvent> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.event.StoredEvent as _obj_ "
                        + "where _obj_.eventId > :eventId "
                        + "order by _obj_.eventId", StoredEvent.class);
        query.setParameter("eventId", aStoredEventId);
        return query.list();
    }

    @Override
    public StoredEvent append(DomainEvent aDomainEvent) {
        String eventSerialization = EventSerializer.instance().serialize(aDomainEvent);
        StoredEvent storedEvent = new StoredEvent(aDomainEvent.getClass().getName(),
                aDomainEvent.occurredOn(),
                eventSerialization);
        this.sessionFactory.getCurrentSession().persist(storedEvent);
        return storedEvent;
    }

    @Override
    public void close() {
        // no-op
    }

    @Override
    public long countStoredEvents() {
        Query<Long> query = this.sessionFactory.getCurrentSession()
                .createQuery("select count(*) from com.saasovation.common.event.StoredEvent", Long.class);
        return query.uniqueResult();
    }

    @Override
    public long minEventId() {
        Query<StoredEvent> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.event.StoredEvent as _obj_ " +
                        "order by _obj_.eventId ", StoredEvent.class);
        List<StoredEvent> storedEvents = query.setMaxResults(1).list();
        return storedEvents.isEmpty() ? 0 : storedEvents.getFirst().eventId();
    }

    @Override
    public long maxEventId() {
        Query<StoredEvent> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.event.StoredEvent as _obj_ " +
                        "order by _obj_.eventId desc ", StoredEvent.class);
        List<StoredEvent> storedEvents = query.setMaxResults(1).list();
        return storedEvents.isEmpty() ? 0 : storedEvents.getFirst().eventId();
    }
}
